package cn.com.xuhx.testMapper;

import cn.com.xuhx.mapper.ParamMapper;
import cn.com.xuhx.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 参数传递
 */
public class ParamTest {

    private SqlSession sqlSession = null;

    @Before
    public void getSQLSession() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //设置需要手动提交事务
        //sqlSession = build.openSession();
        //设置自动提交事务
        sqlSession = build.openSession(true);
    }

    @After
    public void closeSQLSession(){
        sqlSession.clearCache();
        sqlSession.close();
    }

    /**
     * 一个参数映射
     */
    @Test
    public void testQuery(){
        ParamMapper mapper = sqlSession.getMapper(ParamMapper.class);
        User user = mapper.queryUserByID(2);
        System.out.println(user);
    }

    /**
     * map参数
     */
    @Test
    public void testQueryByMap(){
        ParamMapper mapper = sqlSession.getMapper(ParamMapper.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("age",23);
        map.put("tel","18115188222");
        List<User> users = mapper.queryUserBySelf(map);
        System.out.println(users);
    }

    /**
     * 多个参数映射
     */
    @Test
    public void testQueryMoreparam(){
        ParamMapper mapper = sqlSession.getMapper(ParamMapper.class);
        List<User> users = mapper.queryUserByAgeAndTel(23, "18115188222");
        System.out.println(users);
    }

    /**
     * 多个参数映射（命名参数）
     */
    @Test
    public void testQueryMoreparam2(){
        ParamMapper mapper = sqlSession.getMapper(ParamMapper.class);
        List<User> users = mapper.queryUserByAgeAndTel2(23, "18115188222");
        System.out.println(users);
    }
}
